package com.augurit.gzcgwsp.hwgz.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONObject;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.jbpm.api.ProcessEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.web.struts2.Struts2Utils;
import com.augurit.common.base.action.BaseAction;
import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.common.syscode.service.ISysCodeService;
import com.augurit.common.syscode.web.form.SysCodeForm;
import com.augurit.common.system.web.auth.form.LoginUserForm;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gzcgwsp.commonex.util.lang.DateUtilsEX;
import com.augurit.gzcgwsp.hwgz.entity.YwHwShSqb;
import com.augurit.gzcgwsp.hwgz.service.IYwHwShSqbService;
import com.augurit.gzcgwsp.hwgz.web.form.YwHwShSqbForm;
import com.augurit.gzcgwsp.printDoc.service.IYwPrintDocService;
import com.augurit.gzcgwsp.printDoc.web.form.YwPrintDocForm;
import com.augurit.gzcgwsp.wfex.app.doc.IOaDocCodeServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfBusTemplateServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfTemplateAttachmentRefServiceEX;
import com.augurit.gzcgwsp.wfex.bi.web.form.WfTemplateAttachmentRefFormEX;
import com.augurit.gzcgwsp.wfex.common.service.IWfServiceEX;
import com.augurit.gzcgwsp.wfex.common.util.WfUtilsEX;
import com.augurit.gzcgwsp.ywcmn.entity.CertificateNo;
import com.augurit.gzcgwsp.ywcmn.service.ICertificateNoService;
import com.augurit.gzcgwsp.ywcmn.service.IYwComQyxxService;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComQyxxForm;
import com.augurit.wf.bi.web.form.WfBusInstanceTaskForm;
import com.augurit.wf.bi.web.form.WfBusTemplateForm;
import com.augurit.wf.common.constant.WfConstant;
import com.augurit.wf.common.entity.Jbpm4HistTask;
import com.augurit.wf.common.form.WfBusSaveResult;
import com.augurit.wf.common.service.IWfBusClientService;
import com.augurit.wf.common.service.IWfService;
import com.augurit.wf.common.util.WfUtils;
import com.augurit.wf.common.web.WfBusClientAction;
@SuppressWarnings("serial")
@Results({
	@Result(name = CrudActionSupport.RELOAD, location = "yw-hw-sh-sqb.action", type = "redirect"),
	@Result(name = CrudActionSupport.SUCCESS, location = "/gzcgwsp/hwgz/YwHwShSqb/YwHwShSqb.jsp"),
	@Result(name = CrudActionSupport.INPUT, location = "/gzcgwsp/hwgz/YwHwShSqb/YwHwShSqb-input.jsp"),
	@Result(name = "preViewHwgg", location = "/gzcgwsp/hwgz/YwHwShSqb/preViewHwgg.jsp"),
	@Result(name = "gzViewXkz", location = "/gzcgwsp/hwgz/YwHwShSqb/gzViewXkz.jsp"),
	@Result(name = "preViewWqHwgg", location = "/gzcgwsp/hwgz/YwHwShSqb/preViewWqHwgg.jsp"),
	@Result(name = "preViewDhtHwgg", location = "/gzcgwsp/hwgz/YwHwShSqb/preViewDhtHwgg.jsp"),
	@Result(name = "printHwgg", location = "/gzcgwsp/hwgz/YwHwShSqb/printHwgg.jsp"),
	@Result(name = "printHwgg", location = "/gzcgwsp/hwgz/YwHwShSqb/printHwgg.jsp"),
	@Result(name = WfConstant.PRINT_DIR, location = WfConstant.PRINT_DIR_JSP),
	@Result(name = WfConstant.PRINT, location = WfConstant.PRINT_JSP),
    @Result(name = "printviewHwgg", location = "/gzcgwsp/wfex/client/wf-printExcelEx.jsp"),
    @Result(name = WfConstant.MAKE_DOCUMENT, location = "/gzcgwsp/wfex/client/common/make-document.jsp"),
})
public class YwHwShSqbAction extends WfBusClientAction<YwHwShSqbForm>{
    @Autowired
    private IWfServiceEX wfServiceEX;
    @Autowired
	private IWfService wfService;
	@Autowired
	private IYwHwShSqbService ywHwShSqbService;
    @Autowired
    private IOaDocCodeServiceEX oaDocCodeServiceEX;
    @Autowired
	private IYwPrintDocService ywPrintDocService;
	@Autowired
    private IWfBusTemplateServiceEX wfBusTemplateServiceEX;
	@Autowired
	private IYwComQyxxService qyxxService;
    @Autowired
    private ProcessEngine processEngine;
    @Autowired
    private ISysCodeService syscodeService;
    @Autowired
	private ICertificateNoService certificateNoService;
    @Autowired
    private IWfTemplateAttachmentRefServiceEX wfTemplateAttachmentRefServiceEX;
    
	private YwHwShSqbForm form;
	private Long[] checkedIds;
	private Page<YwHwShSqbForm> page = new Page<YwHwShSqbForm>(10);
	private SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
	/**
     * 控件方式套打资质证书
     * @return
     */
    public String printnewHwgg(){
        try {
           String tempPath="Templates/hwgg/hwggszz.xls";  
           String printtype=this.getRequest().getParameter("printtype");
           if(form.getGgxs() != null){    //设置类型
               form.setGgxsStr(ggxsStr(form.getGgxs()));
           }
           String ggxsStr="";//设置规格
           if(form.getGgggtCd()!=null && form.getGgggtHd()!=null){
           	ggxsStr+=form.getGgggtCd()+"*"+form.getGgggtKd()+"*"+form.getGgggtHd();
           }else if(form.getGgggtCd()!=null){
           	ggxsStr+=form.getGgggtCd()+"*"+form.getGgggtKd();
           }
       	if(form.getGgggdCd()!=null && form.getGgggdHd()!=null){
       		ggxsStr+=form.getGgggdCd()+"*"+form.getGgggdKd()+"*"+form.getGgggdHd();
       	}else if(form.getGgggoCd()!=null){
       		ggxsStr+=form.getGgggdCd()+"*"+form.getGgggdKd();
           }
       	if(form.getGgggoKd()!=null && form.getGgggoHd()!=null){
       		ggxsStr+=form.getGgggtCd()+"*"+form.getGgggtKd()+"*"+form.getGgggoHd();
       	}else if(form.getGgggoHd()!=null){
       		ggxsStr+=form.getGgggoCd()+"*"+form.getGgggoKd();
           }
           if(form.getGgxs() != null){    //设置类型
               form.setGgxsStr(ggxsStr(form.getGgxs()));
           }
           if(StringUtils.isBlank(form.getSzggStr())){
        	   form.setSzggStr(ggxsStr);  //设置规格
           }
		   if(StringUtils.isNotBlank(form.getSzggData())){
	        	form.setSzggStr(form.getSzggData());
	        }
           String context=getRequest().getSession().getServletContext().getRealPath("");   
           tempPath=this.ywHwShSqbService.writeSslybData(context,printtype,form);
           getRequest().setAttribute("templateFilePath",tempPath);
       } catch (Exception e) {

       }
        return "printviewHwgg";
    }	
    
    public String gzViewXkz(){

        String ggxsStr="";//设置规格
        if(form.getGgggtCd()!=null && form.getGgggtHd()!=null &&form.getGgggtHd()!=null){
        	ggxsStr+=form.getGgggtCd()+"*"+form.getGgggtKd()+"*"+form.getGgggtHd();
        }else if(form.getGgggtCd()!=null){
        	ggxsStr+=form.getGgggtCd()+"*"+form.getGgggtKd();
        }
    	if(form.getGgggdCd()!=null && form.getGgggdHd()!=null && form.getGgggdHd()!=null){
    		ggxsStr+=form.getGgggdCd()+"*"+form.getGgggdKd()+"*"+form.getGgggdHd();
    	}else if(form.getGgggdCd()!=null){
    		ggxsStr+=form.getGgggdCd()+"*"+form.getGgggdKd();
        }
    	if(form.getGgggoKd()!=null && form.getGgggoHd()!=null && form.getGgggoCd()!=null){
    		ggxsStr+=form.getGgggtCd()+"*"+form.getGgggtKd()+"*"+form.getGgggoHd();
    	}else if(form.getGgggoCd()!=null){
    		ggxsStr+=form.getGgggoCd()+"*"+form.getGgggoKd();
        }
        if(form.getGgxs() != null){    //设置类型
            form.setGgxsStr(ggxsStr(form.getGgxs()));
        }
        if(StringUtils.isBlank(form.getSzggStr())){
        	form.setSzggStr(ggxsStr);  //设置规格
        }
    	String activityName = super.getParameter("hjmc");
		String id=super.getParameter("id");
		String selectType = super.getParameter("selectType");
		if(StringUtils.isBlank(selectType)){
			selectType=form.getPrinttype();
		}
	    BaseAction.getRequest().setAttribute("printtype", selectType);
		if ("wq".equals(selectType)) {
			
		      BaseAction.getRequest().setAttribute("selectType", "围墙");
        }
		BaseAction.getRequest().setAttribute("activityName", activityName);		
        utilWriteDate();    //设置时间
      //流水号
		CertificateNo certificateNo =new CertificateNo();
		boolean exist = certificateNoService.getNo(Long.parseLong(id), 4);
		System.out.println("exist:"+exist);
		if (!exist) {
			certificateNo.setAjid(Long.parseLong(id));
			certificateNo.setZstype(4);
			certificateNoService.save(certificateNo);
			Long maxNum = certificateNoService.getMaxNum(4);
			String szzh = String.valueOf(maxNum + 1);
			while (szzh.length() < 5) {
				szzh = "0" + szzh;
			}
			form.setSzzh(szzh);
			  if(StringUtils.isNotBlank(form.getSzggData())){
		        	form.setSzggStr(form.getSzggData());
		        }
			//ywHwShSqbService.save(form);
			System.out.println("exist");
		} else {
			System.out.println("else");
			form.setSzzh(form.getSzzh());
		}
		Calendar cal = Calendar.getInstance() ;
        cal.add(Calendar.YEAR, 5);
        System.out.println(cal.getTime());
        if(form.getStartyear() == null){
            //form.setEndyear(DateUtilsEX.convertNumber2ChineseByDay(cal.get(Calendar.YEAR)));
            form.setStartyear(cal.get(Calendar.YEAR)+"");
        }
        if(form.getStartmonth() == null){
            //form.setEndmonth(DateUtilsEX.convertNumber2Chinese(cal.get(Calendar.MONTH)+1));
            form.setStartmonth(cal.get(Calendar.MONTH)+1+"");
        }
        if(form.getStartday() == null){
            //form.setEndday(DateUtilsEX.convertNumber2ChineseByDay(cal.get(Calendar.DATE)));
            form.setStartday(cal.get(Calendar.DATE)+"");
        }
		
        if(form.getStartyear() == null){
            //form.setEndyear(DateUtilsEX.convertNumber2ChineseByDay(cal.get(Calendar.YEAR)));
            form.setStartyear(cal.get(Calendar.YEAR)+"");
        }
        if(form.getStartmonth() == null){
            //form.setEndmonth(DateUtilsEX.convertNumber2Chinese(cal.get(Calendar.MONTH)+1));
            form.setStartmonth(cal.get(Calendar.MONTH)+1+"");
        }
        if(form.getStartday() == null){
            //form.setEndday(DateUtilsEX.convertNumber2ChineseByDay(cal.get(Calendar.DATE)));
            form.setStartday(cal.get(Calendar.DATE)+"");
        }
        String printtype=this.getRequest().getParameter("printtype");
        String tempPath="Templates/hwgg/hwggszz.xls";  
        String context=getRequest().getSession().getServletContext().getRealPath("");   
        tempPath=this.ywHwShSqbService.writeSslybData(context,printtype,form);
        getRequest().setAttribute("templateFilePath",tempPath);
		return "gzViewXkz";    
	}
    
    public void setGzXkz(){

        String ggxsStr="";//设置规格
        if(form.getGgggtCd()!=null && form.getGgggtHd()!=null &&form.getGgggtHd()!=null){
        	ggxsStr+=form.getGgggtCd()+"*"+form.getGgggtKd()+"*"+form.getGgggtHd();
        }else if(form.getGgggtCd()!=null){
        	ggxsStr+=form.getGgggtCd()+"*"+form.getGgggtKd();
        }
    	if(form.getGgggdCd()!=null && form.getGgggdHd()!=null && form.getGgggdHd()!=null){
    		ggxsStr+=form.getGgggdCd()+"*"+form.getGgggdKd()+"*"+form.getGgggdHd();
    	}else if(form.getGgggdCd()!=null){
    		ggxsStr+=form.getGgggdCd()+"*"+form.getGgggdKd();
        }
    	if(form.getGgggoKd()!=null && form.getGgggoHd()!=null && form.getGgggoCd()!=null){
    		ggxsStr+=form.getGgggtCd()+"*"+form.getGgggtKd()+"*"+form.getGgggoHd();
    	}else if(form.getGgggoCd()!=null){
    		ggxsStr+=form.getGgggoCd()+"*"+form.getGgggoKd();
        }
        if(form.getGgxs() != null){    //设置类型
            form.setGgxsStr(ggxsStr(form.getGgxs()));
        }
        if(StringUtils.isBlank(form.getSzggStr())){
        	form.setSzggStr(ggxsStr);  //设置规格
        }
    	String activityName = super.getParameter("hjmc");
		String id=super.getParameter("id");
		String selectType = super.getParameter("selectType");
		if(StringUtils.isBlank(selectType)){
			selectType=form.getPrinttype();
		}
	    BaseAction.getRequest().setAttribute("printtype", selectType);
		if ("wq".equals(selectType)) {
			
		      BaseAction.getRequest().setAttribute("selectType", "围墙");
        }
		BaseAction.getRequest().setAttribute("activityName", activityName);		
        utilWriteDate();    //设置时间
      //流水号
		CertificateNo certificateNo =new CertificateNo();
		boolean exist = certificateNoService.getNo(Long.parseLong(id), 4);
		System.out.println("exist:"+exist);
		if (!exist) {
			certificateNo.setAjid(Long.parseLong(id));
			certificateNo.setZstype(4);
			certificateNoService.save(certificateNo);
			Long maxNum = certificateNoService.getMaxNum(4);
			String szzh = String.valueOf(maxNum + 1);
			while (szzh.length() < 5) {
				szzh = "0" + szzh;
			}
			form.setSzzh(szzh);
			  if(StringUtils.isNotBlank(form.getSzggData())){
		        	form.setSzggStr(form.getSzggData());
		        }
			//ywHwShSqbService.save(form);
			System.out.println("exist");
		} else {
			System.out.println("else");
			form.setSzzh(form.getSzzh());
		}
		Calendar cal = Calendar.getInstance() ;
        cal.add(Calendar.YEAR, 5);
        System.out.println(cal.getTime());
        if(form.getStartyear() == null){
            //form.setEndyear(DateUtilsEX.convertNumber2ChineseByDay(cal.get(Calendar.YEAR)));
            form.setStartyear(cal.get(Calendar.YEAR)+"");
        }
        if(form.getStartmonth() == null){
            //form.setEndmonth(DateUtilsEX.convertNumber2Chinese(cal.get(Calendar.MONTH)+1));
            form.setStartmonth(cal.get(Calendar.MONTH)+1+"");
        }
        if(form.getStartday() == null){
            //form.setEndday(DateUtilsEX.convertNumber2ChineseByDay(cal.get(Calendar.DATE)));
            form.setStartday(cal.get(Calendar.DATE)+"");
        }
		
        if(form.getStartyear() == null){
            //form.setEndyear(DateUtilsEX.convertNumber2ChineseByDay(cal.get(Calendar.YEAR)));
            form.setStartyear(cal.get(Calendar.YEAR)+"");
        }
        if(form.getStartmonth() == null){
            //form.setEndmonth(DateUtilsEX.convertNumber2Chinese(cal.get(Calendar.MONTH)+1));
            form.setStartmonth(cal.get(Calendar.MONTH)+1+"");
        }
        if(form.getStartday() == null){
            //form.setEndday(DateUtilsEX.convertNumber2ChineseByDay(cal.get(Calendar.DATE)));
            form.setStartday(cal.get(Calendar.DATE)+"");
        }
        String printtype=this.getRequest().getParameter("printtype");
        String tempPath="Templates/hwgg/hwggszz.xls";  
        String context=getRequest().getSession().getServletContext().getRealPath("");   
        tempPath=this.ywHwShSqbService.writeSslybData(context,printtype,form);
        getRequest().setAttribute("templateFilePath",tempPath);   
	}
    
    
	/**
     * 套打户外广告设置证
     * @return
     */
    public String preViewHwgg(){
        String ggxsStr="";//设置规格
        if(form.getGgggtCd()!=null && form.getGgggtHd()!=null &&form.getGgggtHd()!=null){
        	ggxsStr+=form.getGgggtCd()+"*"+form.getGgggtKd()+"*"+form.getGgggtHd();
        }else if(form.getGgggtCd()!=null){
        	ggxsStr+=form.getGgggtCd()+"*"+form.getGgggtKd();
        }
    	if(form.getGgggdCd()!=null && form.getGgggdHd()!=null && form.getGgggdHd()!=null){
    		ggxsStr+=form.getGgggdCd()+"*"+form.getGgggdKd()+"*"+form.getGgggdHd();
    	}else if(form.getGgggdCd()!=null){
    		ggxsStr+=form.getGgggdCd()+"*"+form.getGgggdKd();
        }
    	if(form.getGgggoKd()!=null && form.getGgggoHd()!=null && form.getGgggoCd()!=null){
    		ggxsStr+=form.getGgggtCd()+"*"+form.getGgggtKd()+"*"+form.getGgggoHd();
    	}else if(form.getGgggoCd()!=null){
    		ggxsStr+=form.getGgggoCd()+"*"+form.getGgggoKd();
        }
    	if(StringUtils.isBlank(form.getGgxsStr())){
    		form.setGgxsStr(ggxsStr(form.getGgxs()));
    	}
//        if(form.getGgxs() != null){    //设置类型
//            form.setGgxsStr(ggxsStr(form.getGgxs()));
//        }
        if(StringUtils.isBlank(form.getSzggStr())){
        	form.setSzggStr(ggxsStr);  //设置规格
        }
    	String activityName = super.getParameter("hjmc");
		String id=super.getParameter("id");
		String selectType = super.getParameter("selectType");
		if(StringUtils.isNotBlank(selectType)){
			try {
				selectType = new String(selectType.getBytes("iso-8859-1"), "utf-8").trim();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(StringUtils.isBlank(selectType)){
			selectType=form.getPrinttype();
		}
	    BaseAction.getRequest().setAttribute("printtype", selectType);
		if ("wq".equals(selectType)) {
			
		      BaseAction.getRequest().setAttribute("selectType", "围墙");
        }
		BaseAction.getRequest().setAttribute("activityName", activityName);		
        utilWriteDate();    //设置时间
      //流水号
		CertificateNo certificateNo =new CertificateNo();
		boolean exist = certificateNoService.getNo(Long.parseLong(id), 4);
		System.out.println("exist:"+exist);
		if (!exist) {
			certificateNo.setAjid(Long.parseLong(id));
			certificateNo.setZstype(4);
			certificateNoService.save(certificateNo);
			Long maxNum = certificateNoService.getMaxNum(4);
			String szzh = String.valueOf(maxNum + 1);
			while (szzh.length() < 5) {
				szzh = "0" + szzh;
			}
			form.setSzzh(szzh);
			  if(StringUtils.isNotBlank(form.getSzggData())){
		        	form.setSzggStr(form.getSzggData());
		        }
			//ywHwShSqbService.save(form);
			System.out.println("exist");
		} else {
			System.out.println("else");
			form.setSzzh(form.getSzzh());
		}
		Calendar cal = Calendar.getInstance() ;
        cal.add(Calendar.YEAR, 5);
        System.out.println(cal.getTime());
        if(form.getStartyear() == null){
            //form.setEndyear(DateUtilsEX.convertNumber2ChineseByDay(cal.get(Calendar.YEAR)));
            form.setStartyear(cal.get(Calendar.YEAR)+"");
        }
        if(form.getStartmonth() == null){
            //form.setEndmonth(DateUtilsEX.convertNumber2Chinese(cal.get(Calendar.MONTH)+1));
            form.setStartmonth(cal.get(Calendar.MONTH)+1+"");
        }
        if(form.getStartday() == null){
            //form.setEndday(DateUtilsEX.convertNumber2ChineseByDay(cal.get(Calendar.DATE)));
            form.setStartday(cal.get(Calendar.DATE)+"");
        }
		
        if(form.getStartyear() == null){
            //form.setEndyear(DateUtilsEX.convertNumber2ChineseByDay(cal.get(Calendar.YEAR)));
            form.setStartyear(cal.get(Calendar.YEAR)+"");
        }
        if(form.getStartmonth() == null){
            //form.setEndmonth(DateUtilsEX.convertNumber2Chinese(cal.get(Calendar.MONTH)+1));
            form.setStartmonth(cal.get(Calendar.MONTH)+1+"");
        }
        if(form.getStartday() == null){
            //form.setEndday(DateUtilsEX.convertNumber2ChineseByDay(cal.get(Calendar.DATE)));
            form.setStartday(cal.get(Calendar.DATE)+"");
        }
        
        if("dzgz".equals(activityName)){
        	   setGzXkz();
        }
        
        if ("wq".equals(selectType)) {
        	return "preViewWqHwgg";
		}else if ("dht".equals(selectType)){
			return "preViewDhtHwgg";
		}else{
			return "preViewHwgg";
		}
        
    }
    /**
     * 套打户外广告设置证
     * @return
     */
    public String printHwgg(){
        ywHwShSqbService.save(form);
        return "printHwgg";
    }
    
    /**
     * 设置类型辅助方法
     * @param ggxs
     * @return
     */
    private String ggxsStr(String ggxs){
        if(ggxs == null || "".equals(ggxs)) return "";
        StringBuffer str = new StringBuffer("");
        String[] gg = ggxs.split(",");
        String[] attr = new String[]{"", "展示牌", "灯箱", "霓虹灯", "电子显示牌（屏）", "实体字", "充气物", "模型", "其它"};
        for(int i = 0; i < attr.length; i++){
            for(int j = 0; j < gg.length; j++){
                try {
					if(Integer.parseInt(gg[j].trim()) == i){
					    str.append(attr[i]+",");
					}
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
            }
        }
        if(str.length()>0){
        	 return str.substring(0, str.length() - 1);
        }else{
        	return "";
        }
       
    }
    

    
    
    public String wfBusSave() {
    	try{
    	String isYsl = super.getParameter("isYsl");
        if (form.getQyid() == null) {
            YwComQyxxForm qyxxForm = qyxxService.getFormBySqdw(form.getSqdw(),form.getTemplateCode());
            if (qyxxForm != null) {
                WfUtils.renderWfFailtureJson("该企业名称已经存在，请点击选择企业从企业列表中选择该企业！");
                return null;
            }
        }
        
        WfBusInstanceTaskForm task = this.wfBusSave((IWfBusClientService)ywHwShSqbService, form, YwHwShSqb.class.getSimpleName());
        String durationExpression = wfServiceEX.getProcDueExpressIonByTaskInstDbid(task.getTaskInstDbid());
        if (form.getDfsj() == null) {
            Date dfsj = wfServiceEX.calculateDueDate(form.getSqrq(), durationExpression);
            form.setDfsj(dfsj);
            this.save();
        }
        if (StringUtils.isNotBlank(isYsl) && "1".equals(isYsl)) {
//            processEngine.getExecutionService().jumpToActivity(task.getExecutionId(), "cksa");
        	String executionId =  processEngine.getHistoryService().createHistoryTaskQuery().taskId(task.getTaskInstDbid().toString()).uniqueResult().getExecutionId();
            processEngine.getExecutionService().jumpToActivity(executionId, "cksa");
            form.setYsl(null);
            ywHwShSqbService.changeYslState(form.getId(), 2l,null);
        }
        WfUtils.renderWfBusSaveJson(task, form);
        
    	}catch (Exception e) {
    		 WfUtils.renderWfFailtureJson("内容太长或者字段类型错误！");
    		 
		}
    	return null;
    }
    
    public String wfBusYslTuih() throws Exception {
    	try {
    		ywHwShSqbService.wfBusYslTuih(form, this.getLoginUser());
			WfBusSaveResult result = new WfBusSaveResult(true, null);
			result.setTask(new WfBusInstanceTaskForm());
			Struts2Utils.renderJson(result);
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
        return null;
    }
    
    public String printcz() throws Exception {
    	String taskId=getRequest().getParameter("taskInstDbid");
    	String activName="";
		if(StringUtils.isNotBlank(taskId)){
		  	WfBusInstanceTaskForm instance = wfService.getWfBusInstanceTaskById(Long.valueOf(taskId), this.getLoginUserName());
			activName=instance.getActivityName();
		    getRequest().setAttribute("activName", activName);
		}else{
			 getRequest().setAttribute("activName", "");
		}
		 BaseAction.getRequest().setAttribute("ywId", form.getId());
        if(form.getId() != null && form.getId() > 0){
            List<YwPrintDocForm> ywPrintDocFormList = ywPrintDocService.get(form.getTemplateCode(), form.getFileCode(), form.getId());
            if(ywPrintDocFormList!=null && ywPrintDocFormList.size()>0){
                return WfConstant.PRINT_DIR;
            }
        }
        return WfUtilsEX.wfBusPrint(form,form.getId(),activName);
    }

    /**
     * 制文
     * @return
     * @throws Exception
     */
    public String makeDocument() throws Exception {
        if (StringUtils.isNotBlank(form.getRedHeadFileId())) {
            String redHeadFilePath = wfBusTemplateServiceEX.getPrintTemplatePath(Long.parseLong(form.getRedHeadFileId()));
            form.setRedHeadFilePath(redHeadFilePath);
        }
         //加载收件通知书里面的附件
		 String isred=getRequest().getParameter("isred");
		 //如果要打印红头
		 if("yes".equals(isred)){
			 String redHeadFilePath = wfBusTemplateServiceEX.getRedFile(form.getTemplateCode());
		      form.setRedHeadFilePath(redHeadFilePath);
		 }
        String templateCode = getTemplateCode();
        if(templateCode != null && templateCode.trim().length() > 0){
            String printTemplatePath = wfBusTemplateServiceEX.getPrintTemplatePath(templateCode, WfTemplateAttachmentRefFormEX.ZHENGWEN_TEMPLATE_TYPE);
            form.setTemplatePath(printTemplatePath);
            WfTemplateAttachmentRefFormEX wfTemplateAttachmentRefFormEX = (WfTemplateAttachmentRefFormEX)wfTemplateAttachmentRefServiceEX.get(Long.parseLong(form.getZhengwenFileId()));
            String zhengwenPath = wfTemplateAttachmentRefFormEX.getFilePath() + "/" + wfTemplateAttachmentRefFormEX.getFileRealName();
            form.setZhengwenPath(zhengwenPath);
            System.out.println("getZhengwenPath:"+form.getZhengwenPath());
            form.setCurDate(DateUtilsEX.convertDate2Chinese(new Date()));
            form.setCurYear(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
            if(form.getCurSeq()==null){
                Long seqcode=oaDocCodeServiceEX.getCurSeqAndAddSeq(templateCode, wfTemplateAttachmentRefFormEX.getFileCode(),form.getId());
                if(seqcode.intValue()<10){
  	        	  form.setCurSeq("0"+String.valueOf(seqcode));
  	        }else{
  	        	  form.setCurSeq(String.valueOf(seqcode));
  	        }
               
            }
            form.setSarq(form.getSqrq());
            WfUtilsEX.wfBusPrint(form);
            BaseAction.getRequest().setAttribute("seq", form.getCurSeq());
            BaseAction.getRequest().setAttribute("fileCode", wfTemplateAttachmentRefFormEX.getFileCode());
            BaseAction.getRequest().setAttribute("entityId", form.getId());
            BaseAction.getRequest().setAttribute("templateId", wfTemplateAttachmentRefFormEX.getId());
//            BaseAction.getRequest().setAttribute("busType", OaFawen.class.getSimpleName());
        }
        return WfConstant.MAKE_DOCUMENT;
    }
    
	@Override
	public String list() throws Exception {
		ywHwShSqbService.search(page, form);
		return SUCCESS;
	}

	/**
	 * �������޸�
	 */
	@Override
	public String input() throws Exception {
		 this.setOpinions();
        
        getRequest().setAttribute("CurrUserName", this.getLoginUser().getUser().getUserName());
        List<SysCodeForm> sqdwlx = syscodeService.getItems("YW_SQDW_LX");
        List<SysCodeForm> ywHbbm = syscodeService.getItems("ALL_HBBM");
        getRequest().setAttribute("sqdwlx", sqdwlx);
        getRequest().setAttribute("ywhbbm", ywHbbm);
		return INPUT;
	}

	/**
	 * �������������޸ĵ�Form����
	 */
	@Override
	public String save() throws Exception {
		ywHwShSqbService.save(form);
		return RELOAD;
	}

	/**
	 * ɾ��һ����¼
	 */
	@Override
	public String delete() throws Exception {
		ywHwShSqbService.delete(form.getId());
		return RELOAD;
	}
	
	/**
	 * ɾ�������¼
	 */
	@Override
	public String deleteMore() throws Exception{
		ywHwShSqbService.delete(checkedIds);
		return RELOAD;
	}
	
	/**
	 * 户外广告设置证的保存
	 * 
	 * @return
	 * @throws IOException 
	 */
	public String saveGgSzz() throws IOException{
		//form.setZsrq(new Date());//设置证书日期
		Map map=getMapByRequest(getRequest());	
		JSONObject jsonObject = JSONObject.fromObject(map); 
		YwHwShSqbForm forms=(YwHwShSqbForm) JSONObject.toBean(jsonObject, YwHwShSqbForm.class);
		String name=(String) map.get("sqdw");
		String szzh=(String) map.get("szzh");
		String ggszd=(String) map.get("ggszd");
		String frxm=(String) map.get("frxm");
		String ggxsStr=(String) map.get("ggxsStr");
		String szggStr=(String) map.get("szggStr");
		String startyear=(String) map.get("startyear");
		String startmonth=(String) map.get("startmonth");
		String startday=(String) map.get("startday");
		String endyear=(String) map.get("endyear");
		String endmonth=(String) map.get("endmonth");
		String endday=(String) map.get("endday");
		String fzjg=(String) map.get("fzjg");
		String bz=(String) map.get("bz");
		String printyear=(String) map.get("printyear");
		String printmonth=(String) map.get("printmonth");
		String printday=(String) map.get("printday");
		String printtype=(String) map.get("printtype");
		if(!"wq".equals(printtype) && !"dht".equals(printtype)){
			form.setPrinttype("gc");
		}
		form.setSzzh(szzh);
		form.setSqdw(name);
		form.setGgszd(ggszd);
		form.setFrxm(frxm);
		form.setGgxsStr(ggxsStr);
		
		form.setSzggData(szggStr);
		form.setStartday(startday);
		form.setStartmonth(startmonth);
		form.setStartyear(startyear);
		form.setEndday(endday);
		form.setEndmonth(endmonth);
		form.setEndyear(endyear);
		form.setFzjg(fzjg);
		form.setBz(bz);
		form.setPrintday(printday);
		form.setPrintmonth(printmonth);
		form.setPrintyear(printyear);
		ywHwShSqbService.save(form);
		getResponse().getWriter().print("success");
		
		return null;
	}
	
	
    //获取request对象中所有参数，并设置到map中
    private  Map getMapByRequest(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration enu = request.getParameterNames();
        while(enu.hasMoreElements()) {   
            String paraName = (String)enu.nextElement();   
            String paraValue = request.getParameter(paraName).trim(); 
            if(paraValue!=null && !"".equals(paraValue)){
                map.put(paraName, paraValue);
            }
        }  
        return map;
    }	
		
	
	/**
	 * ׼��ҳ��ģ��
	 */
	@Override
	protected void prepareModel() throws Exception {
        String id = super.getParameter("id");
        if(StringUtils.isNotBlank(id)){
			form = ywHwShSqbService.get(Long.parseLong(id));
		}else{
			form=new YwHwShSqbForm();
		}
        if(StringUtils.isNotBlank(form.getSzggStr())  ){
        	if(form.getSzggStr().indexOf("null")>0){
        	String szgg=form.getSzggStr();
        	szgg=szgg.replace("null", "");//去掉尾部null
        	szgg=szgg.substring(0,szgg.length()-1);
        	form.setSzggStr(szgg);
        	}
        }
        if(StringUtils.isNotBlank(form.getSzggData())){
        	form.setSzggStr(form.getSzggData());
        }
        if (StringUtils.isBlank(form.getAcceptNo())) {
        	String rq = DateUtilsEX.getYearAndMonthAndDay();
        	form.setAcceptNo("gz26"+rq+"XXXXX");
        }
        if (StringUtils.isBlank(form.getSjr())) {
            form.setSjr(this.getLoginUser().getUser().getUserName());
        }
        
        if (StringUtils.isBlank(form.getJbrxm())) {
            form.setJbrxm(this.getLoginUser().getUser().getUserName());
            form.setJbrtel(this.getLoginUser().getUser().getOfficeTel());
        }
        form.setJbrxm2(this.getLoginUser().getUser().getUserName());
        form.setJbrtel2(this.getLoginUser().getUser().getOfficeTel());
        
        form.setSajg("广州市城市管理委员会");
        form.setSajg2(form.getSajg());
        form.setSajg3(form.getSajg());
        form.setSajg4(form.getSajg());
        form.setLarq(new Date());
        form.setLarq2(new Date());
        form.setLxr2(form.getYwlxr());
        
        if (StringUtils.isBlank(form.getCbyw())) {
            WfBusTemplateForm wfBusTemplateForm = wfBusTemplateServiceEX.getWfBusTemplateService().getByTemplateCode(getTemplateCode());
            if (wfBusTemplateForm != null) {
                form.setCbyw(wfBusTemplateForm.getTemplateName());
            }
        }

        if (StringUtils.isBlank(form.getCbbm())) {
            form.setCbbm("景观处");
        }
        if(form.getFzjg() == null){
            form.setFzjg("广州市城市管理委员会");
        }
        if(form.getBz() == null){
            form.setBz("1、取得《户外广告设置证》后，持该证及有关材料到工商行政管理部门申请办理《户外广告登记证》。2、如需续期，于期限届满30日前向原审批机关申请延期。3、因城市规划、建设、管理等公共利益原因缺需拆除的，应配合予以拆除。");
        }
        
        try {
            if (form.getSarq() == null) {
                form.setSarq(new Date());
            }
            if (form.getCpsj() == null) {
                form.setCpsj(new Date());
            }
            if (form.getDfsj() == null) {
                //form.setDfsj(DateUtils.stringToDate(form.getCpsj().toString(), DateUtils.YEAR_MOUTH_DAY_));
            }
            if (form.getSqrq() == null) {
                form.setSqrq(new Date());
            }
            if(getTaskInstDbid() != null){
            	this.findJbrspUtil();	//获取审批过程中的意见列表
            	this.findCldspUtil();
            	this.findWldspUtil();
            	this.cpbJbrspUtil();
            	this.cpbCldspUtil();
            	this.cpbWldspUtil();
            }
            
          //答复时间
            if(id!=null && StringUtils.isNotBlank(this.getTemplateCode())){
        		Date date=this.wfServiceEX.getDfsjByTempleteCode(this.getTemplateCode(),Long.valueOf(id));
        		form.setDfsj(date);
        	}
        } catch (Exception e) {
            // TODO: handle exception
        }
    	LoginUserForm uform=(LoginUserForm)this.getRequest().getSession().getAttribute("SES_LOGIN_USER");
		String username=uform.getUser().getUserName();
        //获取延期天数
    	int yqtsInt = wfServiceEX.getYqtsByProcInstId(super.getProcInstId());
    	form.setYqts(String.valueOf(yqtsInt));
    	//补交告知原因
    	if(form.getBjgzyy()==null){
    		form.setBjgzyy(this.getOpinion("jbrsl"));
    	}
    	//补交告知时间
    	if(form.getBjgzsj()==null){
    		form.setBjgzsj(new Date());
    	}
//    	//受理告知时间
//    	if(form.getBjslsj()==null){
//    		form.setBjslsj(new Date());
//    	}
    	//补交告知发出人
//    	if(form.getBjgzfcr()==null){
//    		form.setBjgzfcr(username);
//    	}
//        //补交告知受理人
//    	if(form.getSldwcbrxm()==null){
//    		form.setSldwcbrxm(username);
//    		
//    	}
    	//补交告知受理地点
    	if(form.getBjsljtdd()==null){
    		form.setBjsljtdd("广州市城市管理委员会");
    	}
		
	}
	/**
	 * from加载	经办人审批意见列表工具方法
	 */
	private void findJbrspUtil(){
		String names = "'jbrsl' , 'jbrsj'";
		List<Jbpm4HistTask> list = wfServiceEX.getHandleCommentsByTaskInstDbidAndActivityNames(getTaskInstDbid(),names);
		StringBuffer jbrspYj = new StringBuffer();
		for(int i = 0; i < list.size(); i++){
			jbrspYj.append(list.get(i).getHandleComments());
			form.setJbrslsj(list.get(i).getSignTime());
			form.setJbrslxm(list.get(i).getAssigneeName());
		}
		form.setJbrsl(jbrspYj.toString());
	}
	/**
	 * from加载	处领导审批意见列表工具方法
	 */
	private void findCldspUtil(){
		String names = "'cfgldsh' , 'czgldsh'";
		List<Jbpm4HistTask> list = wfServiceEX.getHandleCommentsByTaskInstDbidAndActivityNames(getTaskInstDbid(),names);
		StringBuffer cldspYj = new StringBuffer();
		for(int i = 0; i < list.size(); i++){
			cldspYj.append(list.get(i).getHandleComments());
			form.setCldspsj(list.get(i).getSignTime());
			form.setCldspxm(list.get(i).getAssigneeName());
		}
		form.setCldsp(cldspYj.toString());
	}
	/**
	 * from加载	委领导审批意见列表工具方法
	 */
	private void findWldspUtil(){
		String names = "'wfgldsh' , 'wzgldsp'";
		List<Jbpm4HistTask> list = wfServiceEX.getHandleCommentsByTaskInstDbidAndActivityNames(getTaskInstDbid(),names);
		StringBuffer wldspYj = new StringBuffer();
		for(int i = 0; i < list.size(); i++){
			wldspYj.append(list.get(i).getHandleComments());
			form.setWldspsj(list.get(i).getSignTime());
			form.setWldspxm(list.get(i).getAssigneeName());
		}
		form.setWldsp(wldspYj.toString());
	}
	//打印 呈批表经办人意见
	private void cpbJbrspUtil(){
		String names = "'jbrsl' , 'jbrsj'";
		List<Jbpm4HistTask> list = wfServiceEX.getHandleCommentsByTaskInstDbidAndActivityNames(getTaskInstDbid(),names);
		StringBuffer jbrspYj = new StringBuffer();
		for(int i = 0; i < list.size(); i++){
			jbrspYj.append(list.get(i).getHandleComments()).append("\n")
			.append("    ").append(list.get(i).getAssigneeName()).append("\n")
			.append(simpleDateFormat.format(list.get(i).getSignTime())).append("\n");
		}
		form.setCpbJbryj(jbrspYj.toString());
	}
	//打印  呈批表 处领导意见
	private void cpbCldspUtil(){
		String names = "'cfgldsh' , 'czgldsh'";
		List<Jbpm4HistTask> list = wfServiceEX.getHandleCommentsByTaskInstDbidAndActivityNames(getTaskInstDbid(),names);
		StringBuffer cldspYj = new StringBuffer();
		for(int i = 0; i < list.size(); i++){
			cldspYj.append(list.get(i).getHandleComments()).append("\n")
			.append("    ").append(list.get(i).getAssigneeName()).append("\n")
			.append(simpleDateFormat.format(list.get(i).getSignTime())).append("\n");
		}
		form.setCpbCldyj(cldspYj.toString());
	}
	//打印  呈批表 委领导意见
	private void cpbWldspUtil(){
		String names = "'wfgldsh' , 'wzgldsp'";
		List<Jbpm4HistTask> list = wfServiceEX.getHandleCommentsByTaskInstDbidAndActivityNames(getTaskInstDbid(),names);
		StringBuffer wldspYj = new StringBuffer();
		for(int i = 0; i < list.size(); i++){
			wldspYj.append(list.get(i).getHandleComments()).append("\n")
			.append("    ").append(list.get(i).getAssigneeName()).append("\n")
			.append(simpleDateFormat.format(list.get(i).getSignTime())).append("\n");
		}
		form.setCpbWldyj(wldspYj.toString());
	}
	
	/**
     * 设置户外广告时间设置
     */
    public void utilWriteDate(){
        String startYear = null;
        String startMonth = null;
        String startDay = null;
        String endYear = null;
        String endMonth = null;
        String endDay = null;
        Date sys_date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(sys_date);
        //设置当前时间
        if(form.getPrintyear() == null || "".equals(form.getPrintyear().trim())){
            form.setPrintyear(String.valueOf(cal.get(Calendar.YEAR)));
        }
        if(form.getPrintmonth() == null || "".equals(form.getPrintmonth().trim())){
            form.setPrintmonth(String.valueOf(cal.get(Calendar.MONTH)+1));
        }
        if(form.getPrintday() == null || "".equals(form.getPrintday().trim())){
            form.setPrintday(String.valueOf(cal.get(Calendar.DATE)));
        }
        //设置开始时间
        if(form.getNszqsTime() != null){
            Calendar start = Calendar.getInstance();
            start.setTime(form.getNszqsTime());
            if(form.getStartyear() == null || "".equals(form.getStartyear().trim())){
                startYear = String.valueOf(start.get(Calendar.YEAR));
            }
            if(form.getStartmonth() == null || "".equals(form.getStartmonth().trim())){
                startMonth = String.valueOf(start.get(Calendar.MONTH)+1);
            }
            if(form.getStartday() == null || "".equals(form.getStartday().trim())){
                startDay = String.valueOf(start.get(Calendar.DATE));
            }
        }else{
            if(form.getStartyear() == null || "".equals(form.getStartyear().trim())){
                endYear = String.valueOf(cal.get(Calendar.YEAR));
            }
            if(form.getStartmonth() == null || "".equals(form.getStartmonth().trim())){
                endMonth = String.valueOf(cal.get(Calendar.MONTH)+1);
            }
            if(form.getStartday() == null || "".equals(form.getStartday().trim())){
                endDay = String.valueOf(cal.get(Calendar.DATE));
            }
        }
        //设置结束时间
        if(form.getNszzzTime() != null){
            Calendar end = Calendar.getInstance();
            end.setTime(form.getNszzzTime());
            if(form.getEndyear() == null || "".equals(form.getEndyear().trim())){
                endYear = String.valueOf(end.get(Calendar.YEAR));
            }
            if(form.getEndmonth() == null || "".equals(form.getEndmonth().trim())){
                endMonth = String.valueOf(end.get(Calendar.MONTH)+1);
            }
            if(form.getEndday() == null || "".equals(form.getEndday().trim())){
                endDay = String.valueOf(end.get(Calendar.DATE));
            }
        }else{
            if(form.getEndyear() == null || "".equals(form.getEndyear().trim())){
                endYear = String.valueOf(cal.get(Calendar.YEAR));
            }
            if(form.getEndmonth() == null || "".equals(form.getEndmonth().trim())){
                endMonth = String.valueOf(cal.get(Calendar.MONTH)+1);
            }
            if(form.getEndday() == null || "".equals(form.getEndday().trim())){
                endDay = String.valueOf(cal.get(Calendar.DATE));
            }
        }
        if(startYear != null) form.setStartyear(startYear);
        if(startMonth != null) form.setStartmonth(startMonth);
        if(startDay != null) form.setStartday(startDay);
        if(endYear != null) form.setEndyear(endYear);
        if(endMonth != null) form.setEndmonth(endMonth);
        if(endDay != null) form.setEndday(endDay);
    }
    
	
	public YwHwShSqbForm getModel() {
		return form;
	}
	
	public Long[] getCheckedIds() {
		return checkedIds;
	}

	public void setCheckedIds(Long[] checkedIds) {
		this.checkedIds = checkedIds;
	}
	
	public Page<YwHwShSqbForm> getPage() {
		return page;
	}


	public void setPage(Page<YwHwShSqbForm> page) {
		this.page = page;
	}
}
